package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cungmua.app.R;
import com.cungmua.app.base.BaseAuthenticatedActivity;
import com.cungmua.app.handler.LoginHandler;
import com.cungmua.app.model.request.LoginRequest;
import com.cungmua.app.model.response.LoginResponse;
import com.cungmua.app.task.LoginTask;
import com.cungmua.app.utils.AppUtils;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.entities.Profile;

/**
 * Created by kelvin.nguyen on 6/16/14.
 */
public class LoginActivity extends BaseAuthenticatedActivity implements LoginHandler,View.OnClickListener{
    private Button btnLogin;
    private TextView lblForgotPw;
    private EditText txtEmail;
    private EditText txtPassword;
    private LoginRequest request;
    private Button btnRegister;
    private Button btnFacebook;
    private Button btnYahoo;
    private Button btnGoogle;
    private SimpleFacebook simpleFacebook;

    SimpleFacebook.OnLoginListener onLoginListener = new SimpleFacebook.OnLoginListener() {
        @Override
        public void onLogin() {
            final ProgressDialog pd = ProgressDialog.show(LoginActivity.this,
                    "Loading...", getString(R.string.get_profile));
            simpleFacebook.getProfile(new SimpleFacebook.OnProfileRequestListener() {
                @Override
                public void onComplete(Profile profile) {
                    pd.dismiss();
                    request = new LoginRequest(getDeviceId(), getToken());
                    request.setUid(profile.getId());
                    request.setEmail(profile.getEmail());
                    request.setAuthToken(simpleFacebook.getAccessToken());
                    request.setAuthType("FACEBOOK");

                    new LoginTask(LoginActivity.this, LoginActivity.this).execute(request);
                }

                @Override
                public void onThinking() {
                }

                @Override
                public void onException(Throwable throwable) {
                    pd.dismiss();
                }

                @Override
                public void onFail(String reason) {
                    pd.dismiss();
                    alert(reason);
                }
            });
        }

        @Override
        public void onNotAcceptingPermissions() {
        }

        @Override
        public void onThinking() {
        }

        @Override
        public void onException(Throwable throwable) {
        }

        @Override
        public void onFail(String reason) {
            alert("fail: " + reason);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        simpleFacebook = SimpleFacebook.getInstance(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        simpleFacebook.onActivityResult(this, requestCode, resultCode, data);

        if (requestCode == REQUEST_REGISTER) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
                refreshActivity();
                return;
            }
        } else if (requestCode == REQUEST_GOOGLE_LOGIN || requestCode == REQUEST_YAHOO_LOGIN) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
                refreshActivity();
                return;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_login;
    }

    @Override
    public void updateView() {

    }

    @Override
    public void loadControls(Bundle savedInstanceState) {
        if (getCurrentUser().getId() != 0)
            goToHotDeal();

        txtEmail = (EditText) findViewById(R.id.txtEmail);
        txtPassword = (EditText) findViewById(R.id.txtPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnFacebook = (Button) findViewById(R.id.btnFacebook);
        btnYahoo = (Button) findViewById(R.id.btnYahoo);
        btnGoogle = (Button) findViewById(R.id.btnGoogle);
        lblForgotPw = (TextView) findViewById(R.id.lbl_forgot_pw);

        btnFacebook.setOnClickListener(this);
        btnYahoo.setOnClickListener(this);
        btnGoogle.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        lblForgotPw.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.btnLogin) {
            request = new LoginRequest(getDeviceId(), getToken());
            request.setEmail(txtEmail.getText().toString());
            request.setPassword(AppUtils.MD5(txtPassword.getText().toString()));

            new LoginTask(this, this).execute(request);

        } else if (view.getId() == R.id.btnRegister) {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivityForResult(intent, REQUEST_REGISTER);

        } else if (view.getId() == R.id.btnFacebook) {

            simpleFacebook.login(onLoginListener);

        } else if (view.getId() == R.id.btnYahoo) {

            Intent intent = new Intent(this, WebLoginActivity.class);
            intent.putExtra(IK_METHOD, IK_METHOD_YAHOO);
            startActivityForResult(intent, REQUEST_YAHOO_LOGIN);

        } else if (view.getId() == R.id.btnGoogle) {

            Intent intent = new Intent(this, WebLoginActivity.class);
            intent.putExtra(IK_METHOD, IK_METHOD_GOOGLE);
            startActivityForResult(intent, REQUEST_GOOGLE_LOGIN);

        } else if (view.getId() == R.id.lbl_forgot_pw) {
            Intent intentforgot_pw=new Intent(this,ForgotPasswordActivity.class);
            startActivity(intentforgot_pw);
        }
    }

    @Override
    public void loginSuccess(LoginResponse response) {
        if (request.getAuthType() == "CMC") {
            Log.i("login", "CMC Success");
            setCurrentUser(response.getData());
            setLastLoginRequest(request);
        } else if (request.getAuthType() == "FACEBOOK") {
            setCurrentUser(response.getData());
            request.setAuthType("RESIGN");
            request.setUid("" + response.getData().getId());
            request.setAuthToken(response.getData().getToken());
            setLastLoginRequest(request);
        }

        Toast.makeText(this, R.string.logged_in, Toast.LENGTH_LONG).show();

        setResult(RESULT_OK);
        goToHotDeal(true);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        goToHotDeal();
    }

    public void alert(String message) {
        AlertDialog.Builder dialog;
        dialog = new AlertDialog.Builder(this).setMessage(message)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
        dialog.show();
    }

    @Override
    public void loginFailed(LoginResponse response) {
        alert(response.getErrorMessage(this));
    }
}
